import ColorThief from 'colorthief'
const colorThief = new ColorThief()

export interface ILyric {
    time: number,
    lyric: string,
    uid: number
}

interface IReturnLyric {
    lyric: ILyric[],
}

export const formatMusicLyrics = (lyric?: string): IReturnLyric => {
    if (lyric === '') {
        return { lyric: [{ time: 0, lyric: '这个地方没有歌词！', uid: 520520 }] }
    }
    const lyricObjArr: ILyric[] = [] // 最终生成的歌词数组

    // 将歌曲字符串变成数组，数组每一项就是当前歌词信息
    const lineLyric: any = lyric?.split(/\n/)

    // 匹配中括号里正则的
    const regTime = /\d{2}:\d{2}.\d{2,3}/

    // 循环遍历歌曲数组
    for (let i = 0; i < lineLyric?.length; i++) {
        if (lineLyric[i] === '') continue
        const time: number = formatLyricTime(lineLyric[i].match(regTime)[0])

        if (lineLyric[i].split(']')[1] !== '') {
            lyricObjArr.push({
                time: time,
                lyric: lineLyric[i].split(']')[1],
                uid: parseInt(Math.random().toString().slice(-6))
            })
        }
    }

    return {
        lyric: lyricObjArr
    }
}

const formatLyricTime = (time: string) => {
    const regMin = /.*:/
    const regSec = /:.*\./
    const regMs = /\./

    const min = parseInt((time.match(regMin) as any)[0].slice(0, 2))
    let sec = parseInt((time.match(regSec) as any)[0].slice(1, 3))
    const ms = time.slice((time.match(regMs) as any).index + 1, (time.match(regMs) as any).index + 3)
    if (min !== 0) {
        sec += min * 60
    }
    return Number(sec + '.' + ms)
}
 //根据播放图片切换背景颜色
export const handleSwitchBackground = async (event: Event) => {
    // 获取推荐、侧边栏、页脚的DOM节点
    const recommend: any = document.querySelector('.recommend')
    const aside: any = document.querySelector('aside')
    const footer: any = document.querySelector('footer')
    // 使用colorThief获取图片的调色板，获取3个颜色
    const [c1, c2, c3] = await colorThief.getPalette(event.target, 3)
    // 设置推荐、侧边栏、页脚的背景色
    footer.style.setProperty('--color-1', c1)
    footer.style.setProperty('--color-2', c3)
    recommend.style.setProperty('--color-1', c1)
    recommend.style.setProperty('--color-2', c2)
    aside.style.setProperty('--color-1', c1)
}